<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 2017/4/25
 * Time: 11:24
 */

namespace app\weixin\controller;


use app\common\controller\LiteBase;
use app\common\model\MemberCoupon;
use app\common\util\Assert;
use app\common\util\LoginManager;

class Coupon extends LiteBase
{
    private function divingData($type = 0)
    {
        $m = MemberCoupon::instance()
            ->gotoPage()
            ->where([
                'member_id' => LoginManager::getLoginUserId(),
                'coupon_id' => $type
            ])
            ->select();
        foreach ($m as &$item) {
            $item['create_time'] = ccnn_dateformat($item['create_time']);
        }
        return $m;
    }


    public function divingJSON()
    {
        return $this->jsonSuccess($this->divingData());
    }

    public function diving()
    {

        $this->assign('m', $this->divingData());
        return $this->fetch('diving');
    }

    public function doApply()
    {
        $id = I('post.id');
        if (!empty($id)) {
            $entry = MemberCoupon::instance()->where(['id' => $id])->find();
            if (!empty($entry)) {
                $data = Assert::notEmpty(I('post.'), ['username', 'id', 'workplace', 'telephone']);
                unset($data['id']);
                $data['status'] = 1;
                MemberCoupon::instance()->where(['id' => $id])->save($data);
                return $this->jsonSuccess();
            }
        }
        return $this->jsonFail();
    }

    public function divingTrainJSON()
    {
        return $this->jsonSuccess($this->divingData(1));
    }

    public function divingTrain()
    {
        $this->assign('m', $this->divingData(1));
        return $this->fetch('divingTrain');
    }

    public function apply()
    {
        $id = I('get.id', 0);
        if (!empty($id)) {
            $entry = MemberCoupon::instance()->where(['id' => $id])->find();
            if (!empty($entry)) {
                if ($entry['status'] != 0) {
                    $this->assign('error', '您已使用该活动劵');
                    return $this->fetch();
                }
                $this->assign('m', $entry);
                return $this->fetch();
            }
        }

    }

    public function applyResult()
    {
        $t = I('get.t', 0, 'intval');
        $this->assign('apply', true);
        if ($t == 1) {
            return $this->divingTrain();
        }
        return $this->diving();
    }
}